package com.hqyj.javaSpringBoot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * ParamFilter,删除请求中的“fuck”字符串
 */
@WebFilter(filterName = "paramFilter",value = {"/*"})
public class ParamFilter implements Filter {

    private final static Logger LOGGER=LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("====init()====");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("=====doFilter()=====");
        HttpServletRequest rq= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;

        HttpServletRequestWrapper wrapper=new HttpServletRequestWrapper(rq){
            @Override
            public String getParameter(String name) {
                String value=super.getParameter(name);
                if (StringUtils.isNotBlank(value)){
                    value=value.replaceAll("fuck","***");
                }
                return value;
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                //stream api:数组----list-----数据处理------转化为数据
                return  Arrays.asList(values).stream().map(item ->
                        item.replaceAll("fuck", "***"))
                        .toArray(String[]::new);
            }
        };


        filterChain.doFilter(wrapper,resp);
    }

    @Override
    public void destroy() {
        LOGGER.debug("=====destroy()======");
    }
}
